package com.betterwood.dragon.core.common;

import cn.hutool.core.collection.CollUtil;

import lombok.Data;
import org.springframework.data.domain.Page;

import java.util.Collections;
import java.util.List;

import com.betterwood.dragon.enums.ResultCode;

@Data
public class PageApiResult<T> {

    private List<T> data;

    private Integer pageNum;
    private Integer pageSize;
    private Integer totalPage;
    private Long total;

    private Integer code;

    private String msg;

    public PageApiResult() {
    }

    public PageApiResult(List<T> data, Integer pageNum, Integer pageSize, Integer totalPage, Long total, Integer code,
            String msg) {
        this.data = data;
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.totalPage = totalPage;
        this.total = total;
        this.code = code;
        this.msg = msg;
    }

    /**
     * 将SpringData分页后的list转为分页信息
     */
    public static <T> PageApiResult<T> page(Page<T> pageInfo) {
        PageApiResult<T> result = new PageApiResult<>();
        result.setTotalPage(pageInfo.getTotalPages());
        result.setPageNum(pageInfo.getNumber());
        result.setPageSize(pageInfo.getSize());
        result.setTotal(pageInfo.getTotalElements());
        result.setData(pageInfo.getContent());
        result.setCode(ResultCode.SUCCESS.getCode());
        result.setMsg(ResultCode.SUCCESS.getMsg());
        return result;
    }

    // public static <T> PageApiResult<T> list(List<T> list) {
    // PageApiResult<T> result = new PageApiResult<>();
    // if (CollUtil.isEmpty(list)) {
    // return emptyList();
    // }
    // result.setTotalPage(1);
    // result.setPageNum(0);
    // result.setPageSize(list.size());
    // result.setTotal((long) list.size());
    // result.setData(list);
    // result.setCode(ResultCode.SUCCESS.getCode());
    // result.setMsg(ResultCode.SUCCESS.getMsg());
    // return result;
    // }

    public static <T> PageApiResult<T> emptyList() {
        PageApiResult<T> result = new PageApiResult<>();
        result.setTotalPage(1);
        result.setPageNum(0);
        result.setPageSize(1);
        result.setTotal(0L);
        result.setData(Collections.emptyList());
        result.setCode(ResultCode.SUCCESS.getCode());
        result.setMsg(ResultCode.SUCCESS.getMsg());
        return result;
    }

    public static <T> PageApiResult<T> fail(String msg) {
        PageApiResult<T> result = new PageApiResult<>();
        result.setCode(ResultCode.FAIL.getCode());
        result.setMsg(msg);
        return result;
    }

}